<template>
	<div class="chat-group-side">
		<el-tabs type="border-card">
			<!-- 群聊信息 tab -->
			<el-tab-pane>
				<template #label>
					<el-space>
						<el-icon><InfoFilled /></el-icon>
						<span>群聊信息</span>
					</el-space>
				</template>
				<div class="info-section" v-if="group">
					<el-form 
						class="group-form"
						:model="group"
						label-width="100px"
						label-position="left">
						<el-form-item label="群聊名称">
							<el-input 
								v-model="group.name" 
								:disabled="true"
								maxlength="20">
								<template #prefix>
									<el-icon><ChatRound /></el-icon>
								</template>
							</el-input>
						</el-form-item>

						<el-form-item label="群主">
							<el-input 
								:model-value="ownerName" 
								:disabled="true">
								<template #prefix>
									<el-icon><User /></el-icon>
								</template>
							</el-input>
						</el-form-item>

						<el-form-item label="群公告">
							<el-input
								type="textarea"
								v-model="group.notice"
								:disabled="true"
								:rows="4"
								maxlength="1024"
								placeholder="群主未设置"
								resize="none">
							</el-input>
						</el-form-item>

						<el-form-item label="我的群昵称">
							<el-input
								v-model="group.remarkNickName"
								:disabled="!editing"
								:placeholder="$store.state.userStore.userInfo.nickName"
								maxlength="20">
								<template #prefix>
									<el-icon><Edit /></el-icon>
								</template>
							</el-input>
						</el-form-item>

						<el-form-item label="群聊备注">
							<el-input
								v-model="group.remarkGroupName"
								:disabled="!editing"
								:placeholder="group.name"
								maxlength="20">
								<template #prefix>
									<el-icon><Memo /></el-icon>
								</template>
							</el-input>
						</el-form-item>

						<div class="form-actions">
							<el-space>
								<el-button 
									v-if="editing" 
									type="success" 
									:icon="Check"
									@click="onSaveGroup">
									保存修改
								</el-button>
								<el-button 
									v-if="!editing" 
									type="danger" 
									:icon="Edit"
									@click="editing=!editing">
									编辑
								</el-button>
								<el-button 
									type="danger" 
									v-if="!isOwner" 
									:icon="Close"
									@click="onQuit">
									退出群聊
								</el-button>
							</el-space>
						</div>
					</el-form>
				</div>
				<div v-else class="info-loading">
					<el-empty description="群组信息加载中或不可用..."></el-empty>
				</div>
			</el-tab-pane>

			<!-- 群成员管理 tab -->
			<el-tab-pane>
				<template #label>
					<el-space>
						<el-icon><UserFilled /></el-icon>
						<span>群成员管理</span>
					</el-space>
				</template>
				<div class="members-section" v-if="group && groupMembers">
					<div class="members-header">
						<div class="search-input">
							<el-input
								placeholder="搜索群成员"
								v-model="searchText"
								clearable>
								<template #prefix>
									<el-icon><Search /></el-icon>
								</template>
							</el-input>
						</div>
						<div class="actions">
							<el-button 
								class="add-friend-btn"
								type="danger"
								@click="showAddGroupMember=true"
								title="邀请成员">
								<el-icon><Plus /></el-icon>
								邀请成员
							</el-button>
						</div>
					</div>

					<div class="members-container">
						<div>
							<div class="members-grid">
								<div 
									v-for="member in displayMembers"
									:key="member.id"
									v-show="member && !member.quit && member.showNickName && member.showNickName.includes(searchText)"
									class="member-item"
									@mouseenter="handleMouseEnter(member)"
									@mouseleave="handleMouseLeave(member)">
									<group-member
										:member="member"
										:showDel="false"
										:ownerId="group && group.ownerId"
										:group="group"
										:nameMaxLength="8"
										:isCurrentUserAdmin="isAdmin">
									</group-member>
									<el-icon 
										class="kick-icon" 
										@click="isAdmin ? kickMember(member.userId) : null" 
										v-if="(isAdmin || isOwner) && group && member && member.id !== group.ownerId" 
										v-show="isHovered">
										<Delete />
									</el-icon>
								</div>
							</div>
							<el-empty v-if="displayMembers.length === 0" description="暂无成员" />
							<div v-if="loading" class="loading-text">
								<el-space>
									<el-icon class="is-loading"><Loading /></el-icon>
									<span>加载中...</span>
								</el-space>
							</div>
						</div>
					</div>
				</div>
				<div v-else class="info-loading">
					<el-empty description="群成员数据加载中或不可用..."></el-empty>
				</div>
			</el-tab-pane>
		</el-tabs>

		<!-- 邀请成员弹窗 -->
		<add-group-member 
			v-if="group && groupMembers"
			:visible="showAddGroupMember" 
			:groupId="group && group.id" 
			:members="groupMembers" 
			@reload="$emit('reload')"
			@close="showAddGroupMember=false">
		</add-group-member>
	</div>
</template>

<script>
	import AddGroupMember from '../group/AddGroupMember.vue';
	import GroupMember from '../group/GroupMember.vue';
	import HeadImage from '../common/HeadImage.vue';
	import groupApi from '@/api/im/group';
	import emitter from '@/utils/eventBus';
	// import { 
	// 	InfoFilled,
	// 	UserFilled,
	// 	ChatRound,
	// 	User,
	// 	Edit,
	// 	Memo,
	// 	Check,
	// 	Close,
	// 	Plus,
	// 	Search,
	// 	Delete,
	// 	Loading
	// } from '@element-plus/icons-vue';
	export default {
		name: "chatGroupSide",
		components: {
			AddGroupMember,
			GroupMember,
			HeadImage
		},
		data() {
			return {
				gAPI: new groupApi(),
				searchText: "",
				editing: false,
				showAddGroupMember: false,
				displayMembers: [],
				pageSize: 20,
				currentPage: 1,
				loading: false,
				isHovered: false
			}
		},
		props: {
			group: {
				type: Object
			},
			groupMembers: {
				type: Array
			}
		},
		
		methods: {
			onClose() {
				this.$emit('close');
			},
			initMembersList() {
				// 确保数据有效
				if (!this.groupMembers || !Array.isArray(this.groupMembers)) {
					console.warn('群成员数据不可用或格式不正确');
					this.displayMembers = [];
					return;
				}
				
				// 如果没有成员，直接返回空数组
				if (this.groupMembers.length === 0) {
					console.log('群组中没有成员');
					this.displayMembers = [];
					return;
				}
				
				console.log('开始初始化成员列表，总成员数:', this.groupMembers.length);
				
				this.currentPage = 1;
				this.displayMembers = this.groupMembers.slice(0, this.pageSize);
				console.log(`初始加载了 ${this.displayMembers.length}/${this.groupMembers.length} 名成员`);
				
				if (this.displayMembers.length >= this.groupMembers.length) {
					console.log('所有成员已加载完成');
					return;
				}
				
				this.loadAllMembersRecursively();
			},
			loadAllMembersRecursively() {
				if (!this.groupMembers || !Array.isArray(this.groupMembers)) {
					console.error('群成员数据不可用或格式不正确');
					return;
				}
				
				if (this.displayMembers.length >= this.groupMembers.length) {
					console.log('所有成员已全部加载完成');
					return;
				}
				
				console.log('自动加载更多成员...');
				this.loading = true;
				
				setTimeout(() => {
					const start = this.displayMembers.length;
					const end = start + this.pageSize;
					const newMembers = this.groupMembers.slice(start, Math.min(end, this.groupMembers.length));
					
					this.displayMembers = [...this.displayMembers, ...newMembers];
					console.log(`已加载 ${this.displayMembers.length}/${this.groupMembers.length} 名成员`);
					
					this.loading = false;
					
					this.$nextTick(() => {
						this.loadAllMembersRecursively();
					});
				}, 50);
			},
			loadMoreMembers() {
				if (!this.groupMembers || !Array.isArray(this.groupMembers)) {
					console.error('群成员数据不可用或格式不正确');
					return;
				}
				
				if (this.loading || this.displayMembers.length >= this.groupMembers.length) {
					console.log('已经在加载中或已全部加载完成，跳过此次加载请求');
					return;
				}
				
				console.log('手动触发加载更多成员...');
				this.loading = true;
				
				setTimeout(() => {
					const start = this.displayMembers.length;
					const end = start + this.pageSize;
					const newMembers = this.groupMembers.slice(start, Math.min(end, this.groupMembers.length));
					
					this.displayMembers = [...this.displayMembers, ...newMembers];
					console.log(`已加载 ${this.displayMembers.length}/${this.groupMembers.length} 名成员`);
					
					this.loading = false;
				}, 100);
			},
			handleScroll(e) {
				if (!e || !e.target) return;
				
				if (!this.groupMembers || !Array.isArray(this.groupMembers)) {
					return;
				}
				
				const target = e.target;
				const scrollHeight = target.scrollHeight;
				const scrollTop = target.scrollTop;
				const clientHeight = target.clientHeight;
				
				if (scrollHeight - scrollTop - clientHeight < 50 && !this.loading && this.displayMembers.length < this.groupMembers.length) {
					console.log('滚动触发加载更多');
					this.loadMoreMembers();
				}
			},
			loadGroupMembers() {
				if (!this.group || !this.group.id) {
					console.error('群组信息不完整，无法加载成员');
					return;
				}
				
				this.$http({
					url: `/group/members/${this.group.id}`,
					 method: "get"
				}).then((members) => {
					this.groupMembers = members;
					this.initMembersList();
				}).catch((error) => {
					console.error('加载群成员失败:', error);
				});
			},
			onSaveGroup() {
				if (!this.group) {
					this.$message.error('群组信息不完整，无法执行此操作');
					return;
				}
				
				let vo = this.group;
				this.$http({
					url: "/group/modify",
					method: "put",
					data: vo
				}).then((group) => {
					if (group && group.zid && !group.id) {
						group.id = group.zid;
					}
					this.$store.commit("updateGroup", group);
					this.$emit('reload');
					this.$message.success("修改成功");
				})
			},
			onQuit() {
				this.$confirm('退出群聊后将不再接受群里的消息，确认退出吗？', '确认退出?', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					if (!this.group || !this.group.id) {
						this.$message.error('群组信息不完整，无法执行此操作');
						return;
					}
					
					this.$http({
						url: `/group/quit/${this.group.id}`,
						method: 'delete'
					}).then(() => {
						this.$store.commit("removeGroup", this.group.id);
						this.$store.commit("activeGroup", -1);
						this.$store.commit("removeGroupChat", this.group.id);
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消'
						});          
					});
				})
			},
			kickMember(userId) {
				this.$confirm('确认要踢出该成员吗?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const groupId = this.group && this.group.id;
					if (!groupId) {
						this.$message.error('群组信息不完整，无法执行此操作');
						return;
					}
					this.$http({
						url: `/group/kick2?groupId=` + groupId + '&userId=' + userId,
						method: 'DELETE',
					}).then(() => {
						this.$message.success('成员已被踢出');
						this.groupMembers.splice(this.groupMembers.findIndex(member => member.userId === userId), 1);
						this.initMembersList();
					}).catch(error => {
						this.$message.error('踢出成员失败: ' + error.message);
					});
				});
			},
			handleMouseEnter(member) {
				this.isHovered = true;
			},
			handleMouseLeave(member) {
				this.isHovered = false;
			},
			updateInfo() {
				this.editing = false;
				// 更新群组信息
				let group = JSON.parse(JSON.stringify(this.group));
				if (!group) {
					this.$message.error('群组信息不完整，无法执行此操作');
					return;
				}
				// 组织数据
				if(!group.id && group.zid) {
					group.id = group.zid;
				}
			},
			saveGroupInfo() {
				this.editing = false;
				// 更新群组信息
				let group = JSON.parse(JSON.stringify(this.group));
				if (!group) {
					this.$message.error('群组信息不完整，无法执行此操作');
					return;
				}
				// 组织数据
				if(!group.id && group.zid) {
					group.id = group.zid;
				}
			},
			quitGroup() {
				this.$confirm('确认要退出该群聊吗? 退出后将不再接收此群的消息通知', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					if (!this.group || !this.group.id) {
						this.$message.error('群组信息不完整，无法执行此操作');
						return;
					}
					
					this.$http({
						url: `/group/quit/${this.group.id}`,
						method: 'DELETE',
					}).then(() => {
						this.$store.commit("removeGroup", this.group.id);
						this.$emit('close');
						this.$store.commit("removeGroupChat", this.group.id);
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消'
						});          
					});
				})
			},
			reloadMembers() {
				if (!this.group || !this.group.id) {
					console.error('群组信息不完整，无法加载成员');
					return;
				}
				
				// 加载群成员信息
				this.$http({
					url: `/group/members/${this.group.id}`,
					method: 'get'
				}).then((groupMembers) => {
					this.groupMembers = groupMembers;
					this.initMembersList();
				}).catch((error) => {
					console.error('加载群成员失败:', error);
				});
			}
		},
		computed: {
			isAdmin() {
				let users = this.$store.state.userStore.userInfo;
				return this.group && this.group.ownerId && users.id === this.group.ownerId ? true : false;
			},
			ownerName() {
				if (!this.group || !this.group.ownerId || !this.groupMembers) return '';
				let member = this.groupMembers.find((m) => m.userId == this.group.ownerId);
				return member && member.showNickName;
			},
			isOwner() {
				if (!this.group || !this.group.ownerId) return false;
				return this.group.ownerId == this.$store.state.userStore.userInfo.id;
			}
		},
		watch: {
			searchText() {
				console.log('搜索文本更改:', this.searchText);
				this.$nextTick(() => {
					this.initMembersList();
				});
			},
			groupMembers: {
				handler(newMembers, oldMembers) {
					console.log('群成员数据更新:', newMembers?.length, '旧数据长度:', oldMembers?.length);
					if (newMembers && newMembers.length > 0) {
						this.$nextTick(() => {
							this.initMembersList();
						});
					}
				},
				immediate: true
			},
			group: {
				handler(newGroup) {
					console.log('群组数据更新:', newGroup);
				},
				immediate: true
			}
		},
		created() {
			// 允许一点时间等待数据加载
			setTimeout(() => {
				this.$nextTick(() => {
					// 不再阻止组件继续初始化
					// 即使没有group数据也应该显示占位信息
					if (!this.group) {
						console.warn('群组数据尚未加载完成，将显示占位信息');
					}
					
					// 为成员列表容器添加滚动事件监听
					const container = document.querySelector('.members-container');
					if (container) {
						container.addEventListener('scroll', this.handleScroll);
					} else {
						console.warn('未找到成员列表容器元素');
					}
				});
			}, 200); // 给一点延迟确保DOM已渲染
		},
		beforeUnmount() {
			const container = document.querySelector('.members-container');
			if (container) {
				container.removeEventListener('scroll', this.handleScroll);
			}
		}
	}
</script>

<style lang="scss">
	.chat-group-side {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: var(--el-bg-color);
		width: 380px;

		:deep(.el-tabs) {
			height: 100%;
			display: flex;
			flex-direction: column;
			
			.el-tabs__content {
				flex: 1;
				overflow: hidden;
				padding: 0;

				.el-tab-pane {
					height: 100%;
					overflow: auto;
				}
			}
		}

		// 基本信息区域
		.info-section {
			padding: var(--el-padding-large);
			
			.group-form {
				max-width: 100%;
				
				:deep(.el-form-item) {
					margin-bottom: var(--el-margin-medium);

					.el-input__wrapper {
						box-shadow: 0 0 0 1px var(--el-border-color) inset;
					}

					.el-input__wrapper:hover {
						box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
					}
				}

				.form-actions {
					margin-top: var(--el-margin-large);
					text-align: right;
				}
			}
		}

		// 成员管理区域
		.members-section {
			height: 100%;
			padding: var(--el-padding-medium);
			display: flex;
			flex-direction: column;
			overflow: hidden;

			.members-header {
				flex-shrink: 0;
				margin-bottom: 24px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				gap: var(--el-gap-base);
				padding: 0 10px;

				.search-input {
					flex: 1;
					
					:deep(.el-input__wrapper) {
						padding: 8px 15px;
						box-shadow: 0 0 0 1px var(--el-border-color) inset;
						
						&:hover {
							box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
						}
						
						.el-input__inner {
							font-size: 14px;
						}
					}
				}

				.actions {
					.el-button {
						height: 40px;
						padding: 0 20px;
					}
				}
			}

			.members-container {
				flex: 1;
				height: 400px;
				overflow-y: auto;
				overflow-x: hidden;
				padding: 10px;
				border: 1px solid #f0f0f0;
				border-radius: 4px;
				background-color: #fafafa;
				position: relative;
				
				&::-webkit-scrollbar {
					width: 6px;
				}
				
				&::-webkit-scrollbar-thumb {
					background: #bbb;
					border-radius: 3px;
					
					&:hover {
						background: #999;
					}
				}
				
				&::-webkit-scrollbar-track {
					background: transparent;
				}

				.members-grid {
					display: grid;
					grid-template-columns: repeat(2, 1fr);
					gap: 20px 15px;
					padding: 5px;
					justify-items: center;
				}

				.member-item {
					width: 140px;
					display: flex;
					justify-content: center;
					align-items: center;
					position: relative;
					padding: 15px 10px;
					border-radius: var(--el-border-radius-base);
					transition: all 0.3s;
					background-color: var(--el-fill-color-blank);
					border: 1px solid var(--el-border-color-lighter);

					&:hover {
						background-color: var(--el-fill-color-light);
						transform: translateY(-2px);
						box-shadow: var(--el-box-shadow-light);
					}
				}

				.loading-text {
					text-align: center;
					padding: var(--el-padding-medium);
					color: var(--el-text-color-secondary);
				}
			}
		}

		.kick-icon {
			position: absolute;
			top: 8px;
			right: 8px;
			display: none;
			font-size: var(--el-font-size-small);
			color: var(--el-color-danger);
			cursor: pointer;
			z-index: 100;
			background-color: var(--el-bg-color);
			border-radius: 50%;
			padding: 6px;
			box-shadow: none;

			&:hover {
				background-color: var(--el-color-danger-light-9);
				color: var(--el-color-danger);
			}
		}

		.member-item:hover .kick-icon {
			display: block;
		}

		:deep(.group-member-item) {
			width: 100%;
			padding: 8px;
			text-align: center;
			
			.member-avatar {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-bottom: 12px;
				
				.head-image {
					margin: 0 auto;
					width: 60px;
					height: 60px;
					border-radius: 50%;
					border: 2px solid var(--el-border-color-lighter);
					transition: all 0.3s;
					
					&:hover {
						border-color: var(--el-color-primary);
						background-color: var(--el-fill-color-light);
					}
				}
			}

			.member-name {
				font-size: 14px;
				color: var(--el-text-color-primary);
				margin-top: 8px;
				width: 100%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				height: 20px;
				max-width: 120px;
				margin: 0 auto;
				line-height: 20px;
			}

			.member-role {
				font-size: 12px;
				color: var(--el-text-color-secondary);
				margin-top: 4px;
			}
		}
	}
</style>
